/* 
* Copyright (C) 2011-2018 ShenZhen iBOXSaaS Information Technology Co.,Ltd. 
* 
* All right reserved. 
* 
* This software is the confidential and proprietary 
* information of iBOXSaaS Company of China. 
* ("Confidential Information"). You shall not disclose 
* such Confidential Information and shall use it only 
* in accordance with the terms of the contract agreement 
* you entered into with iBOXSaaS inc. 
* 
*/

package com.iboxpay.open.gateway.routes;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute;
import org.springframework.util.StringUtils;

import com.iboxpay.open.gateway.basedata.BaseData;

import lombok.Data;

/**
 * 
 * OpenGatewayRouteLocator.java
 * @author xuxiao
 * @date 2018/06/15
 */
@Data
public class OpenGatewayRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {

	private BaseData baseData;

	private ZuulProperties zuulProperties;

	public OpenGatewayRouteLocator(String servletPath, ZuulProperties properties) {
		super(servletPath, properties);
		this.zuulProperties = properties;
	}

	@Override
	public void refresh() {
		super.doRefresh();
	}

	@Override
	protected Map<String, ZuulRoute> locateRoutes() {
		Map<String, ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>();
		// 从application.properties中加载路由信息
		routesMap.putAll(super.locateRoutes());
		// 从db中加载路由信息
		routesMap.putAll(baseData.zuulRouteMap);
		// 优化一下配置
		Map<String, ZuulProperties.ZuulRoute> values = new LinkedHashMap<>();
		for (Map.Entry<String, ZuulProperties.ZuulRoute> entry : routesMap.entrySet()) {
			String path = entry.getKey();
			// Prepend with slash if not already present.
			if (!path.startsWith("/")) {
				path = "/" + path;
			}
			if (StringUtils.hasText(this.zuulProperties.getPrefix())) {
				path = this.zuulProperties.getPrefix() + path;
				if (!path.startsWith("/")) {
					path = "/" + path;
				}
			}
			values.put(path, entry.getValue());
		}
		return values;
	}

}
